import cv2
import os



def create_frame(address_slow):
    # 获取当前脚本所在的文件夹路径
    current_file_path = os.path.abspath(__file__)
    current_dir_path = os.path.dirname(current_file_path)

    print(address_slow)
    filename = os.path.basename(address_slow)
    print("提取出的文件名:", filename)

    target_dir_path = None  # 初始化目标目录路径

    # 解析文件名以确定目标目录路径
    # 解析文件名以确定目标目录路径
    if 'wired' in filename or 'wireless' in filename:
        connection_type = 'wired' if 'wired' in filename else 'wireless'
        base_dir = 'vd_static' if '_vd' in filename else 'static'

        if '720' in filename:
            resolution = '720'
        elif '1080' in filename:
            resolution = '1080'
        elif '480' in filename:
            resolution = '480'
        else:
            resolution = None

        if resolution:
            target_dir_path = os.path.join(
                os.path.dirname(current_dir_path),
                base_dir,
                f"{connection_type}_{resolution}"
            )

    if target_dir_path is None:
        print('文件名字错误，命名格式应该包含“有线”或者“wired”， “分辨率”等字样')
        return None
    else:
        # 如果目标目录不存在，则创建它
        if not os.path.exists(target_dir_path):
            os.makedirs(target_dir_path)
            print(f"已创建目录: {target_dir_path}")
        print(f"目标目录路径: {target_dir_path}")

    # 打开视频文件
    cap = cv2.VideoCapture(address_slow)
    # 检查视频是否成功打开
    if not cap.isOpened():
        print("无法打开视频文件")
        return None

    # 获取视频的帧率
    fps = cap.get(cv2.CAP_PROP_FPS)
    print(f"视频帧率为: {fps} 帧/秒")

    # print('wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww')
    # print(f'已创建了存放全部图片的路径{target_dir_path}')
    # print('wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww')
    try:

        frame_count = 0
        while True:
            # 读取视频的每一帧
            ret, frame = cap.read()
            # 如果视频读取完毕，退出循环
            if not ret:
                break
            # 获取当前帧的时间戳（秒）
            timestamp = frame_count / fps
            # 构建保存帧的文件名，这里以time_0001.234.jpg、time_0002.567.jpg等格式保存
            frame_filename = f"time_{timestamp:.5f}.jpg"
            # 构建完整的目标文件路径
            output_file_path = os.path.join(target_dir_path, frame_filename)
            # 保存当前帧为图像文件
            cv2.imwrite(output_file_path, frame)
            frame_count += 1
        # 释放视频资源
        cap.release()

    except Exception as e:
        print(f'截取视频帧为图片失败，原因是{e}')
        raise e

    return target_dir_path
    print(f"共截取并保存了 {frame_count} 帧图像到 {target_dir_path} 目录下。")


#
if __name__ == '__main__':
    create_frame('/Users/zltest/Desktop/wireless_1080_vd_output.mp4')